from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from .models import Message
from .serializers import MessageSerializer
from django.contrib.auth import get_user_model
from django.db.models import Q
from users.serializers import UserSerializer  # 确保有 username 和 avatar 字段
User = get_user_model()

class MessageListView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, user_id):
        other_user = User.objects.get(id=user_id)
        messages = Message.objects.filter(
            sender__in=[request.user, other_user],
            receiver__in=[request.user, other_user]
        ).order_by('timestamp')
        serializer = MessageSerializer(messages, many=True)
        return Response(serializer.data)


class SendMessageView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        receiver_id = request.data.get('receiver')
        content = request.data.get('content')
        receiver = User.objects.get(id=receiver_id)
        msg = Message.objects.create(sender=request.user, receiver=receiver, content=content)
        serializer = MessageSerializer(msg)
        return Response(serializer.data)


# message/views.py


class ChatUserListView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user
        sent = Message.objects.filter(sender=user).values_list('receiver', flat=True)
        received = Message.objects.filter(receiver=user).values_list('sender', flat=True)
        user_ids = set(sent) | set(received)
        users = User.objects.filter(id__in=user_ids)
        data = UserSerializer(users, many=True).data
        return Response(data)
